package a07_二叉树;

import java.util.Arrays;

/**
 * <p>
 * a15_最大二叉树
 * </p>
 * 遍历方式：必须是前序，中左右
 *
 * @author flyduck
 * @since 2024-09-24
 */
public class a19_最大二叉树 {
    public static void main(String[] args) {
        int[] nums = new int[]{3,2,1,6,0,5};
        TreeNode treeNode = constructMaximumBinaryTree(nums);
        System.out.println(treeNode);
    }

    public static TreeNode constructMaximumBinaryTree(int[] nums) {//1、确定递归的返回值、参数
        if (nums.length == 0) {
            return null;
        }
        //找出最大值
        int maxValue = Integer.MIN_VALUE;
        int maxIdx = 0;
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] > maxValue){
                maxValue = nums[i];
                maxIdx = i;
            }
        }
        TreeNode root = new TreeNode(maxValue);

        //左右区间
        root.left = constructMaximumBinaryTree(splitArray(nums, 0, maxIdx - 1));
        root.right = constructMaximumBinaryTree(splitArray(nums, maxIdx + 1, nums.length - 1));
        return root;

    }

    public static int[] splitArray(int[] oldArray,int leftIdx,int rightIdx){
        int[] newArray = new int[rightIdx - leftIdx + 1];
        for (int i = 0; i < newArray.length; i++) {
            newArray[i] = oldArray[leftIdx];
            leftIdx++;
        }
        return newArray;
    }
}
